<?php

/**
 * LEAGUEMan
 * 
 * Copyright (C) 2007 Marko Bischof
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
class LM_Table_Project extends LM_Table
{
    /** @var int Primary Key */
    public $project_id;
    /** @var string project name */
    public $project_name;
    /** @var int references LM_Table_League */
    public $project_league;
    /** @var int references LM_Table_Season */
    public $project_season;
    /** @var string */
    public $project_template;
    /** @var string */
    public $eventtypes;
    /** @var int references mosUser */
    public $project_admin;
    /** @var int references LM_Table_Team */
    public $project_team;
    /** @var int rerences LM_Table_Round */
    public $project_cur_round;
    /** @var int minimum Round */
    public $project_min_round;
    /** @var int maximum Round */
    public $project_max_round;
    /** @var bool published */
    public $published;
    /** @var bool finished */
    public $finished;
    /** @var string serialized array */
    public $params;
    private $_params;
    private $_last_round;
    private $_current_round;
    private $_next_round;
    private $_template;
    private $_rounds;

    /**
     * constructor
     * @param object $db mosDatabase
     */
    public function __construct($db)
    {
        parent::__construct('#__leagueman_project', 'project_id', $db);
    }

    public function getID()
    {
        return $this->project_id;
    }

    public function getName()
    {
        return $this->project_name;
    }

    public function getTemplate()
    {
        return $this->project_template;
    }

    public function getLeague()
    {
        return $this->project_league;
    }

    public function getLeagueName()
    {
        $league = LM::getLMTable("League");
        if ($league->load($this->getLeague())) {
            return $league->getName();
        } else {
            return "";
        }
    }

    public function getSeason()
    {
        return $this->project_season;
    }

    public function getSeasonName()
    {
        $season = LM::getLMTable("Season");
        if ($season->load($this->getSeason())) {
            return $season->getName();
        } else {
            return "";
        }
    }

    public function getAdmin()
    {
        return $this->project_admin;
    }

    public function getMinRound()
    {
        return $this->project_min_round;
    }

    public function getMaxRound()
    {
        return $this->project_max_round;
    }

    public function getPublished()
    {
        return $this->published;
    }

    public function getFinished()
    {
        return $this->finished;
    }

    public function getFavTeam()
    {
        return $this->project_team;
    }

    public function isAdmin()
    {
        global $my;

        return strtolower($my->usertype) == 'admin' || $my->id == $this->getAdmin();
    }

    public function getRoundBox()
    {
        $rounds = array();
        foreach ($this->getRounds() AS $round) {
            if ($this->getCurrentRound() == $round->ordering) {
                $rounds[] = mosHTML::makeOption($round->ordering, $round->round_name . " (current)");
            } else {
                $rounds[] = mosHTML::makeOption($round->ordering, $round->round_name);
            }
        }
        return $rounds;
    }

    public function getModes()
    {
        return array(
            mosHTML::makeOption(0, "Total"),
            mosHTML::makeOption(1, "Home"),
            mosHTML::makeOption(2, "Away")
        );
    }

    public function getPositions()
    {
        $sql = "SELECT * FROM #__leagueman_position
				 WHERE position_projecttype = " . $this->_db->Quote($this->getTemplate()) . "
			  ORDER BY ordering";
        $this->_db->setQuery($sql);
        return $this->_db->loadObjectList();
    }

    public function getRounds($field = "")
    {
        $sql = "SELECT * FROM #__leagueman_round
				 WHERE round_project = " . $this->getID() . " 
			  ORDER BY ordering";
        $this->_db->setQuery($sql);
        return $this->_db->loadObjectList($field);
    }

    public function hasRounds()
    {
        return count($this->getRounds()) > 0;
    }

    public function getPrevRound()
    {

        if ($this->getCurrentRound() > $this->getMinRound()) {
            return $this->getCurrentRound() - 1;
        } else {
            return false;
        }
    }

    public function getCurrentRound()
    {
        return $this->project_cur_round;
    }

    public function getNextRound()
    {

        if ($this->getCurrentRound() < $this->getMaxRound()) {
            return $this->getCurrentRound() + 1;
        } else {
            return false;
        }
    }

    public function getValidRound($ordering)
    {

        if ($ordering >= $this->getMinRound() && $ordering <= $this->getMaxRound()) {
            return $ordering;
        } else {
            return false;
        }
    }

    public function getRows($limitstart = 0, $limit = 10)
    {

        $limitstart = intval($limitstart);
        $limit = intval($limit);

        $sql = "SELECT a.*,l.league_name, s.season_name, u1.name AS admin
				  FROM #__leagueman_project AS a
			 LEFT JOIN #__leagueman_league AS l ON l.league_id = a.project_league
			 LEFT JOIN #__leagueman_season AS s ON s.season_id = a.project_season
			 LEFT JOIN #__users AS u1 ON u1.id = a.project_admin"
                . $this->getFilter() . "
			  ORDER BY a.project_id
			  	 LIMIT $limitstart, $limit";

        $this->_db->setQuery($sql);

        return $this->_db->loadObjectList();
    }

    public function getTotalRows()
    {
        $sql = "SELECT COUNT(a.project_id)
				  FROM #__leagueman_project AS a
			 LEFT JOIN #__leagueman_league AS l ON l.league_id = a.project_league
			 LEFT JOIN #__leagueman_season AS s ON s.season_id = a.project_season
			 LEFT JOIN #__users AS u1 ON u1.id = a.project_admin"
                . $this->getFilter();
        $this->_db->setQuery($sql);
        return $this->_db->loadResult();
    }

    public function load($oid = null)
    {
        $k = $this->_tbl_key;

        if ($oid !== null) {
            $this->$k = $oid;
        }

        $oid = $this->$k;

        if ($oid === null) {
            return false;
        }

        $class_vars = get_class_vars(get_class($this));
        foreach ($class_vars as $name => $value) {
            if (($name != $k) and ($name != "_db") and ($name != "_tbl") and ($name != "_tbl_key")) {
                $this->$name = $value;
            }
        }

        $this->reset();

        $query = "SELECT * FROM $this->_tbl WHERE $this->_tbl_key = '$oid'";
        $this->_db->setQuery($query);

        if ($this->_db->loadObject($this)) {
            $this->_params = @unserialize($this->params);
            return true;
        } else {
            return false;
        }
    }

    public function getParams()
    {
        return $this->_params;
    }

    public function getParam($name, $default = 0)
    {
        return isset($this->_params[$name]) ? $this->_params[$name] : $default;
    }

    public function getEventtypes()
    {
        if (!empty($this->eventtypes)) {
            return (array) unserialize($this->eventtypes);
        } else {
            return array();
        }
    }

    public function getGroupBox()
    {

        $groups = array();

        if ($this->getParam("groups_supported", 0) == 1) {
            $list = $this->getParam("project_groups", "");
            if (!empty($list)) {
                $vals = explode(",", $list);
                foreach ($vals as $val) {
                    $groups[] = mosHTML::makeOption("$val", "$val");
                }
            }
        }

        return $groups;
    }

    public function getTeams($field = "")
    {

        $query = "SELECT tt.*, t.*
                	FROM #__leagueman_team t
          	  INNER JOIN #__leagueman_teammap tt ON tt.teammap_team = t.team_id
               	   WHERE tt.teammap_project = " . intval($this->getID());

        $this->_db->setQuery($query);
        return $this->_db->loadObjectList($field);
    }

    public function getTeamBox()
    {

        $teams = $this->getTeams();

        $options = array();
        foreach ($teams as $team) {
            $options[] = mosHTML::makeOption($team->team_id, $team->team_name);
        }

        return $options;
    }

    public function getTeamToolBox()
    {

        $teams = $this->getTeams();

        $options = array();
        foreach ($teams as $team) {
            $options[] = mosHTML::makeOption($team->teammap_id, $team->team_name);
        }

        return $options;
    }

    public function getForumCategory()
    {
        return $this->getParam("forum", 0);
    }

    public function createForum()
    {
        $database = $this->_db;

        $name = $database->Quote($this->getName());

        $database->setQuery("SELECT MAX(ordering) FROM jos_sb_categories WHERE parent = 0");
        $ordering = intval($database->loadResult());

        $database->setQuery(
                "INSERT INTO jos_sb_categories
				(id, parent, name, ordering, published) 
					VALUES ('', 0, $name, $ordering, 1)");

        if ($database->query()) {
            $lastid = $database->insertid();
            $this->createSubForums($lastid);
            return $lastid;
        }

        return 0;
    }

    public function createSubForums($parent)
    {
        $database = $this->_db;

        $parent = $database->Quote(intval($parent));

        $database->setQuery(
                "INSERT INTO jos_sb_categories
				(id, parent, name, ordering, published) 
					VALUES ('', $parent, 'Allgmeines', 1, 1)");
        $database->query();

        $database->setQuery(
                "INSERT INTO jos_sb_categories
				(id, parent, name, ordering, published) 
					VALUES ('', $parent, 'Spieltage', 2, 1)");
        $database->query();

        $i = 2;
        $teams = $this->getTeams();
        foreach ($teams AS $team) {

            $teamname = $database->Quote($team->team_name);
            $ordering = $database->Quote(intval(++$i));

            $database->setQuery(
                    "INSERT INTO jos_sb_categories
					(id, parent, name, ordering, published) 
						VALUES ('', $parent, $teamname, $ordering, 1)");
            $database->query();
        }
    }

    public function getContentItemSection()
    {

        $section_cat = $this->getParam("section_category", "");

        $section = 0;
        if (!empty($section_cat)) {

            list($section, ) = explode(":", $section_cat);
        }

        return $section;
    }

    public function getContentItemCategory()
    {

        $section_cat = $this->getParam("section_category", "");

        $category = 0;
        if (!empty($section_cat)) {

            list(, $category) = explode(":", $section_cat);
        }

        return $category;
    }

    public function getColors()
    {
        $s = substr($this->getParam("colors", ""), 0, -1);

        $arr1 = array();
        if (trim($s) != "") {
            $arr1 = explode(";", $s);
        }

        $colors = array();

        for ($i = 0; $i < count($arr1); $i++) {
            $arr2 = explode(",", $arr1[$i]);
            if (count($arr2) != 4) {
                break;
            }

            $colors[$i]["from"] = $arr2[0];
            $colors[$i]["to"] = $arr2[1];
            $colors[$i]["color"] = $arr2[2];
            $colors[$i]["description"] = $arr2[3];
        }

        return $colors;
    }

    function getTopPlayer($type)
    {

        switch ($type) {

            case 'topused':
                $ordering = "pm.cnt_matches DESC";
                break;

            case 'topshooter':
                $ordering = "pm.cnt_goals DESC";
                break;

            case 'topscorer':
                $ordering = "pm.cnt_goals DESC, pm.cnt_assissts DESC";
                break;

            case 'yellowsinner':
                $ordering = "pm.cnt_yellow DESC";
                break;

            case 'yellowredsinner':
                $ordering = "pm.cnt_yellow_red DESC";
                break;

            case 'redsinner':
                $ordering = "pm.cnt_red DESC";
                break;
        }

        $sql = "SELECT p.*, pm.*, t.*
				  FROM #__leagueman_playermap pm
			INNER JOIN #__leagueman_player p ON p.player_id = pm.playermap_player
			INNER JOIN #__leagueman_team t ON t.team_id = pm.playermap_team
				 WHERE pm.playermap_project = " . $this->getID() . "
			  ORDER BY $ordering
			  LIMIT 10";
        $this->_db->setQuery($sql);
        return $this->_db->loadObjectList();
    }

}